package jdsk.iria;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	private Uri fileUri;
	private String selectedImagePath;
	private static String filemanagerstring;
	private static String studentName;
	private static String teacherName;
	private static String fileName;
	private static int numOfWords;
	private static String numOfWordsString;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// used for custom font
		TextView txt = (TextView) findViewById(R.id.textView3);
		Typeface font = Typeface
				.createFromAsset(getAssets(), "Courier_New.ttf");
		txt.setTypeface(font);

		((EditText) findViewById(R.id.editText2)).setKeyListener(null);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			studentName = extras.getString("studentName");
			teacherName = extras.getString("teacherName");
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/**
	 * Handles the start button being clicked.
	 * 
	 * @param view
	 */
	public void loadButtonClick(View view) {

		Toast.makeText(this, "  The Load Feature Has Not Been Implemented Yet",
				Toast.LENGTH_LONG).show();

	}

	/***
	 * Handles the "Capture Button" being pushed.
	 * 
	 * @param view
	 * @throws IOException
	 */
	public void captureButtonClick(View view) throws IOException {

		numOfWordsString = ((EditText) findViewById(R.id.editText1)).getText()
				.toString();
		numOfWords = Integer.parseInt(((EditText) findViewById(R.id.editText1))
				.getText().toString());

		if (numOfWordsString.equals("") || numOfWords < 1) {
			Toast.makeText(this, "The Word Count Must Be Greater Than 0",
					Toast.LENGTH_LONG).show();

		} else {
			numOfWords = Integer
					.parseInt(((EditText) findViewById(R.id.editText1))
							.getText().toString());
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			// This saves the picture in folder
			fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file
																// to save the
																// image
			filemanagerstring = fileUri.getPath();
			selectedImagePath = filemanagerstring;
			intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image
																// file name

			// start the image capture Intent
			startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
		}

	}

	/** Create a file Uri for saving an image */
	private static Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/** Create a File for saving an image */
	private static File getOutputMediaFile(int type) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		/**
		 * File mediaStorageDir = new
		 * File(Environment.getExternalStoragePublicDirectory(
		 * Environment.getRootDirectory().getPath()), "IRIA");
		 **/

		File mediaStorageDir = new File(
				Environment.getExternalStorageDirectory(), "IRIA");

		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("IRIA", "failed to create directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			fileName = studentName + "_" + timeStamp;
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ fileName + ".jpg");
		} else {
			return null;
		}

		return mediaFile;
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
				Bundle dataBundle = new Bundle();
				dataBundle.putString("imageFile", filemanagerstring);
				dataBundle.putString("fileName", fileName);
				dataBundle.putString("studentName", studentName);
				dataBundle.putString("teacherName", teacherName);
				dataBundle.putInt("numOfWords", Integer
						.parseInt(((EditText) findViewById(R.id.editText1))
								.getText().toString()));
				Intent myIntent = new Intent(this, TextViewWindow.class);
				myIntent.putExtras(dataBundle);
				startActivity(myIntent);

				// DEBUG PURPOSE - you can delete this if you want
				if (selectedImagePath != null)
					System.out.println(selectedImagePath);
				else
					System.out.println("selectedImagePath is null");
				if (filemanagerstring != null)
					System.out.println(filemanagerstring);
				else
					System.out.println("filemanagerstring is null");

				// NOW WE HAVE OUR WANTED STRING
				if (selectedImagePath != null)
					System.out
							.println("selectedImagePath is the right one for you!");
				else
					System.out
							.println("filemanagerstring is the right one for you!");
			}
		}
	}

	// UPDATED!
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		if (cursor != null) {
			// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
			// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} else
			return null;
	}

}
